import React, { useState } from 'react';
import { Form, Modal } from 'antd';
import CodeMirror from '@uiw/react-codemirror';
import { javascript } from '@codemirror/lang-javascript';
import useControlOptions from '../../hooks/useControlOptions';
import { ScriptSubmitProps } from './ScriptSubmit';
import Icon from './../icon/Icon';
import styles from './style.module.scss';

const FormItem = Form.Item;
const extensions = [javascript({ jsx: true })];

export default () => {
  const { options, changeControlProps: change } = useControlOptions<ScriptSubmitProps>();
  const [visible, setVisible] = useState(false);
  const [codeMirrorValue, setCodeMirrorValue] = useState('');

  function show() {
    setVisible(true);
    setCodeMirrorValue(options.scriptText || '');
  }

  function onOk() {
    setVisible(false);
    change('scriptText', codeMirrorValue);
    setCodeMirrorValue('');
  }

  function onCancel() {
    setVisible(false);
    setCodeMirrorValue('');
  }

  return (
    <>
      <div style={{ position: 'relative' }}>
        <FormItem label='脚本内容'>
          <CodeMirror
            extensions={extensions}
            onChange={(value: string) => change('scriptText', value)}
            value={options.scriptText} />
        </FormItem>
        <Icon
          className={styles.screenIcon}
          icon='&#xe67c;'
          onClick={show} />
      </div>
      <Modal
        visible={visible}
        title='脚本'
        width={1000}
        onCancel={onCancel}
        onOk={onOk}>
        <CodeMirror
          extensions={extensions}
          onChange={setCodeMirrorValue}
          value={codeMirrorValue} />
      </Modal>
    </>
  )
}